package com.cw.demo.grovvy;

import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Date;

public class GrovvyTest {
    public static void main(String[] args) {
        testByFunction();
    }
    public static void testByFunction(){
        ScriptEngineManager factory = new ScriptEngineManager();
        //每次生成一个engine实例
        ScriptEngine engine = factory.getEngineByName("groovy");
        // 初始化Bindings
        Bindings bindings = engine.createBindings();
        // 绑定参数
        bindings.put("date", new Date());
        final String name = "groovy";
        // 定义groovy脚本中执行方法的名称
        final String scriptName = "execute";
        // 定义groovy脚本内容
        final String scriptContent = "def " + scriptName +"(name){" +
                "    println(\"now dateTime is: ${date.getTime()}\");" +
                "    println(\"my name is $name\");" +
                "    return date.getTime() > 0;" +
                "}";
        System.out.println(scriptContent);
        try {
            // 执行脚本
            engine.eval(scriptContent, bindings);
            // 获取执行结果
            Invocable invocable = (Invocable) engine;
            Boolean flag = (Boolean) invocable.invokeFunction(scriptName, name);
            System.out.println("---------------------------------------");
            System.out.println("result is: " + flag);
        } catch (ScriptException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public static void evalScript() throws Exception{
        ScriptEngineManager factory = new ScriptEngineManager();
        //每次生成一个engine实例
        ScriptEngine engine = factory.getEngineByName("groovy");
        System.out.println(engine.toString());
        assert engine != null;
        //javax.script.Bindings
        Bindings binding = engine.createBindings();
        binding.put("date", new Date());
        //如果script文本来自文件,请首先获取文件内容
        engine.eval("def getTime(){return date.getTime();}",binding);
        engine.eval("def sayHello(name,age){return 'Hello,I am ' + name + ',age' + age;}");
        Long time = (Long)((Invocable)engine).invokeFunction("getTime", null);
        System.out.println(time);
        String message = (String)((Invocable)engine).invokeFunction("sayHello", "zhangsan",new Integer(12));
        System.out.println(message);
    }
}
